package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.ViewGroup;

import com.ccj.poptabview.FilterConfig;
import com.ccj.poptabview.PopTabView;
import com.ccj.poptabview.base.BaseFilterTabBean;
import com.ccj.poptabview.bean.FilterGroup;
import com.ccj.poptabview.bean.FilterTabBean;
import com.ccj.poptabview.listener.OnPopTabSetListener;
import com.ccj.poptabview.loader.PopEntityLoaderImp;
import com.ccj.poptabview.loader.ResultLoaderImp;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessPlan;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.CityVO;
import com.digitalchina.lxnsy.entity.CropListVO;
import com.digitalchina.lxnsy.entity.ProductStandardVO;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.viewholder.SelectProductionHolderV2;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/8/21 18:56
 * 修改备注：
 * ================================================
 */
public class SelectProductionActivityV2 extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, OnPopTabSetListener {


    @Bind(R.id.recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.expand_pop)
    PopTabView expandPop;
    private List<ProductStandardVO> voList = new ArrayList<>();

    private RecyclerArrayAdapter adapter;

    private String provinceName = "";
    private String cityName = "";
    private String countyName = "";
    private String cropTypeCode = "";//1
    private String suitCropCode = "";//2

    private List<CityVO> cityVOList = new ArrayList<>();


    // 1级分类
    private List<CropListVO> list = new ArrayList<>();
    // 2级分类
    private List<CropListVO.ChildListBean> list2 = new ArrayList<>();

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_select_production_v2);
        setTitle("选择生产标准");
    }

    @Override
    public void initMember() {

        InputStream inputStream = null;
        try {
            inputStream = getAssets().open("city.txt");
            int size = inputStream.available();
            int len = -1;
            byte[] bytes = new byte[size];
            inputStream.read(bytes);
            inputStream.close();
            String string = new String(bytes);
            cityVOList = FastJsonUtil.getListBeanNoKey(string, CityVO.class);

        } catch (IOException e) {
            e.printStackTrace();
        }


        BusinessPlan.getCropClassification(this, mHandler);

        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new SelectProductionHolderV2(parent);
            }
        });


        onRefresh();
    }

    @Override
    public void addListener() {

        recyclerView.setRefreshListener(this);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                GotoUtil.gotoActivity(SelectProductionActivityV2.this, SelectProductionDetailActivity.class,  "ProductStandardVO", adapter.getAllData().get(position));
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case MSG.MSG_QUERY_PRODUCT_STANDARD_SUCCESS: // 列表
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_QUERY_PRODUCT_STANDARD_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_GET_CROP_CLASSIFICATION_SUCCESS: // 农作物分类
                        setType(msg.obj);
                        break;
                    case MSG.MSG_GET_CROP_CLASSIFICATION_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

        voList = FastJsonUtil.getListBean(object.toString(), "productStandardList", ProductStandardVO.class);

        adapter.clear();

        adapter.addAll(voList);

    }


    private void setType(Object object) {
        list = FastJsonUtil.getListBean(object.toString(), "cropList", CropListVO.class);

        if (list != null && list.size() > 0) {

//            CropListVO vo = new CropListVO();
//            vo.setName("全部");
//            vo.setCode("");
//            List<CropListVO.ChildListBean> vosBeanList = new ArrayList<>();
//            CropListVO.ChildListBean vo2 = new CropListVO.ChildListBean();
//            vo2.setName("全部分类");
//            vo2.setCode("");
//            vosBeanList.add(vo2);
//            vo.setChildList(vosBeanList);

            for (int i = 0; i < list.size(); i++) {
                for (int j = 0; j < list.get(i).getChildList().size(); j++) {
                    // 单层list所有二级分类
                    list2.add(list.get(i).getChildList().get(j));
                }
            }

            //list2.add(0, vo2);


            FilterGroup filterGroup1 = getMyData1();
            FilterGroup filterGroup2 = getMyData2();

            expandPop.setOnPopTabSetListener(this)
                    .setPopEntityLoader(new PopEntityLoaderImp()).setResultLoader(new ResultLoaderImp()); //配置 {筛选类型}  方式
            expandPop.addFilterItem(filterGroup1.getTab_group_name(), filterGroup1.getFilter_tab(), filterGroup1.getTab_group_type(), filterGroup1.getSingle_or_mutiply());
            expandPop.addFilterItem(filterGroup2.getTab_group_name(), filterGroup2.getFilter_tab(), filterGroup2.getTab_group_type(), filterGroup2.getSingle_or_mutiply());

        }

    }

    /**
     * 设置第一组筛选器
     *
     * @return
     */
    public FilterGroup getMyData1() {

        FilterGroup filterGroup = new FilterGroup();

        filterGroup.setTab_group_name("农产品种");
        filterGroup.setTab_group_type(FilterConfig.TYPE_POPWINDOW_LINKED);
        filterGroup.setSingle_or_mutiply(FilterConfig.FILTER_TYPE_SINGLE);

        List<BaseFilterTabBean> singleFilterList = new ArrayList<>();

        FilterTabBean ftb1 = new FilterTabBean();
        List<FilterTabBean.ChildTabBean> cf1 = new ArrayList<>();
        FilterTabBean.ChildTabBean sb1 = new FilterTabBean.ChildTabBean();
        sb1.setTab_name("全部");
        sb1.setTab_id("");
        cf1.add(sb1);
        ftb1.setTab_name("全部分类");
        ftb1.setTab_id("");
        ftb1.setTabs(cf1);
        singleFilterList.add(ftb1);

        for (int i = 0; i < list.size(); i++) {//一级filter
            FilterTabBean singleFilterBean = new FilterTabBean();
            singleFilterBean.setTab_id(list.get(i).getCode());
            singleFilterBean.setTab_name(list.get(i).getName());

            List<FilterTabBean.ChildTabBean> childFilterList = new ArrayList<>();
            for (int j = 0; j < list.get(i).getChildList().size(); j++) {//二级filter
                FilterTabBean.ChildTabBean secondFilterBean = new FilterTabBean.ChildTabBean();
                secondFilterBean.setTab_id(list.get(i).getChildList().get(j).getCode());
                secondFilterBean.setTab_name(list.get(i).getChildList().get(j).getName());
                childFilterList.add(secondFilterBean);
            }

            singleFilterBean.setTabs(childFilterList);
            singleFilterList.add(singleFilterBean);
        }

        filterGroup.setFilter_tab(singleFilterList);
        return filterGroup;

    }


    /**
     * 设置第二组筛选器
     *
     * @return
     */
    public FilterGroup getMyData2() {
        FilterGroup filterGroup = new FilterGroup();

        filterGroup.setTab_group_name("所在地区");
        filterGroup.setTab_group_type(FilterConfig.TYPE_POPWINDOW_LINKED);
        filterGroup.setSingle_or_mutiply(FilterConfig.FILTER_TYPE_SINGLE);

        List<BaseFilterTabBean> singleFilterList = new ArrayList<>();

        FilterTabBean ftb1 = new FilterTabBean();
        List<FilterTabBean.ChildTabBean> cf1 = new ArrayList<>();
        FilterTabBean.ChildTabBean sb1 = new FilterTabBean.ChildTabBean();
        sb1.setTab_name("全国");
        cf1.add(sb1);
        ftb1.setTab_name("全国");
        ftb1.setTabs(cf1);
        singleFilterList.add(ftb1);

        for (int i = 0; i < cityVOList.size(); i++) {//一级filter
            FilterTabBean singleFilterBean = new FilterTabBean();
            singleFilterBean.setTab_name(cityVOList.get(i).getProvinceName());

            List<FilterTabBean.ChildTabBean> childFilterList = new ArrayList<>();
            for (int j = 0; j < cityVOList.get(i).getCitys().size(); j++) {//二级filter
                FilterTabBean.ChildTabBean secondFilterBean = new FilterTabBean.ChildTabBean();
                if (j == 0){
                    FilterTabBean.ChildTabBean sb = new FilterTabBean.ChildTabBean();
                    sb.setTab_name("全省");
                    sb.setTab_id(cityVOList.get(i).getProvinceName());
                    childFilterList.add(sb);
                }
                secondFilterBean.setTab_name(cityVOList.get(i).getCitys().get(j).getCitysName());
                secondFilterBean.setTab_id(cityVOList.get(i).getProvinceName());
                childFilterList.add(secondFilterBean);
            }

            singleFilterBean.setTabs(childFilterList);
            singleFilterList.add(singleFilterBean);
        }

        filterGroup.setFilter_tab(singleFilterList);

        return filterGroup;
    }


    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onRefresh() {
        BusinessPlan.queryProductStandardV2(this, provinceName, cityName, countyName, cropTypeCode, suitCropCode, mHandler);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            if (ActivityTaskManager.getInstance().hasActivity(StandardProductionActivity.class))
                finish();
            else
                GotoUtil.gotoActivity(SelectProductionActivityV2.this, StandardProductionActivity.class, true);
        }
    }

    @Override
    public void onPopTabSet(int index, String lable, Object params, String value) {
        switch (index) {
            case 0:
                suitCropCode = params + "";
                break;
            case 1:

                if ("全国".equals(value)){
                    provinceName = "";
                    cityName = "";
                    countyName = "";
                }else{
                    if ("全省".equals(value)){
                        provinceName = params + "";
                        cityName = "";
                        countyName = "";

                    }else {
                        provinceName = params + "";
                        cityName = value;
                        countyName = "";
                    }
                }

                break;
        }
        onRefresh();
    }
}
